<template>
  <!-- 数据导入对话框 -->
  <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
    <el-upload
        ref="refUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="headers"
        :action="uploadUrl"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :multiple="false"
        :http-request="uploadAction"
        drag>
      <div class="asset-upload-lay">
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" v-if="rootTips" @click.stop="() => {}">
          <el-checkbox v-model="upload.importRoot" />
          {{rootTips}}
        </div>
        <div class="el-upload__tip" v-if="tips" @click.stop="() => {}">
          <el-checkbox v-model="upload.updateSupport" />
          {{tips}}
        </div>
        <span class="el-upload__tip" style="color: red;">仅允许导入xls、xlsx格式的文件。</span>
        <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>-->
      </div>
    </el-upload>
    <template v-slot:footer >
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {computed, ref} from "vue";
import {buildHeaders} from "@/apis";

const refUpload = ref();

const props = withDefaults(defineProps<{
  url: string,
  doUpload: any,
  tips?: string,
  rootTips?: string,
}>(), {});

const upload = ref({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  importRoot: false,
  // 是否更新已经存在的用户数据
  updateSupport: true,
})

const headers = computed(() => {
  const hds: any = {...buildHeaders()};
  hds['Content-Type'] = 'application/x-www-form-urlencoded';
  return hds;
})

const uploadUrl = computed(() => {
  return import.meta.env.VITE_APP_BASE_API + props.url
      + '?updateSupport=' + upload.value.updateSupport
      + '&importRoot=' + upload.value.importRoot;
})

// 文件上传中处理 /uni-center/v1/excel/asset/import/platform
const handleFileUploadProgress = () => {
  upload.value.isUploading = true;
}

// 文件上传成功处理
const handleFileSuccess = () => {
  upload.value.open = false;
  upload.value.isUploading = false;
  refUpload.value.clearFiles();
}

const handleImport = (title: string='数据导入') => {
  upload.value.title = title;
  upload.value.open = true;
}

// 提交上传文件
const  submitFileForm = () => {
  refUpload.value.submit();
}

const uploadAction = async (option: any) => {
  await props.doUpload(option, uploadUrl.value, headers.value)
}

defineExpose({
  handleImport
})

</script>

<style>
.asset-upload-lay {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin: 0 32px;
}

</style>
